package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Value("${out_put_path}")
    private String outPutPath;//从属性文件获取相关信息




    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
       setmealDao.add(setmeal);
       //获取添加后的那条数据的id(mybatis实现)
        Integer setmealId = setmeal.getId();
        //将对应关系添加到中间表中
        setSetmealAndCheckgroup(setmealId,checkgroupIds);
        //将图片保存到redis集合中(带网址)
        this.savePic2Redis(setmeal.getImg());
        //新增套餐后将需要重新生成静态页面
        this.generateMobileStaticHtml();
    }
    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //生成静态页面之前查询当前页面所需信息
        List<Setmeal> list =setmealDao.findAll();
        //需要生成套餐列表静态页面
      this.generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        this.generateMobileSetmealDetailHtml(list);
    }


    //生成静态页面之前查询当前页面所需信息
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map=new HashMap();
        //将所需数据放入map(key一定和页面相同)
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }
    //需要生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    /**
     * 通用生成freemark静态
     * @param templateName 模板名
     * @param htmlPageName 静态页面名
     * @param map 参数
     */
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获取配置对象
        Writer out=null;
        try {
            Template template = configuration.getTemplate(templateName);//获取对应的模板
            //构造输出流,为了周到将静态页面生成到哪里
            out=new FileWriter(new File(outPutPath+"/"+htmlPageName));
            //输出文件(在指定位置生成静态文件)
            template.process(map,out);
            //刷新
            out.flush();
            //关流
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }






 //根据关系添加中间表
    private void setSetmealAndCheckgroup(Integer setmealId, Integer[] checkgroupIds) {

        //判断是否有要绑定的组
        if (checkgroupIds.length>0 && checkgroupIds!=null) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    //将图片名称保存到redis中
    private void savePic2Redis(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }

//分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }
    //查询套餐通过套餐id
    @Override
    public Setmeal findById(Integer id) {
        return  setmealDao.findById(id);

    }
    //查询中间表确定当前id套餐里的检查组
    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return  setmealDao.findCheckGroupIdsBySetmealId(setmealId);

    }
    //删除通过id
    @Override
    public void deleteById(Integer setmealId) {
        setmealDao.deleteById(setmealId);
    }
//删除中间表
    @Override
    public void deleteGroupBySetmealId(Integer setmealId) {
        setmealDao.deleteGroupBySetmealId(setmealId);
    }
//修改套餐
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //首先将中间表关系删除
        setmealDao.deletesetmealcheckgroupBySetmealId(setmeal.getId());
        //将修改套餐数据保存
        setmealDao.editBySetmealId(setmeal);
        //重新建立中间表的管旭
        this.setSetmealAndCheckgroup(setmeal.getId(),checkgroupIds);
    }
//查询所有
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }
//修改套餐并且修改了图片
    @Override
    public void editAndDelteImg(String oldImgUrl,Setmeal setmeal, Integer[] checkgroupIds) {
        //将要修改的图片路径添加到redis中,统一定时删除
        jedisPool.getResource().sadd(RedisConstant.Delete_PIC_DB_RESOURCES,oldImgUrl);
        //将图片保存到差集redis集合中(带网址)
        this.savePic2Redis(setmeal.getImg());
        //首先将中间表关系删除
        setmealDao.deletesetmealcheckgroupBySetmealId(setmeal.getId());
        //将修改套餐数据保存
        setmealDao.editBySetmealId(setmeal);
        //重新建立中间表的管旭
        this.setSetmealAndCheckgroup(setmeal.getId(),checkgroupIds);
    }
    //查询套餐预约占比数据
    @Override
    public List<Map<String, Object>> findSetmealCount() {

        return setmealDao.findSetmealCount();
    }
}
